import Foundation
import Vapor
import NIOCore

struct TencentSMSService {
    private let microserviceBaseURL: String
    private let httpClient: Client
    
    init(microserviceBaseURL: String, httpClient: Client) {
        self.microserviceBaseURL = microserviceBaseURL
        self.httpClient = httpClient
    }
    
    /// Sends an SMS verification code to the specified phone number
    /// - Parameters:
    ///   - phoneNumber: The recipient's phone number
    ///   - code: The verification code to send
    ///   - international: Whether this is an international phone number
    /// - Returns: A success or failure response
    func sendSMS(to phoneNumber: String, code: String, international: Bool = false) async throws {
        // Create the request payload
        struct SMSRequest: Content {
            let phone_number: String
            let code: String
            let international: Bool
        }
        
        let payload = SMSRequest(
            phone_number: phoneNumber,
            code: code,
            international: international
        )
        
        // Create URL
        let url = URI(string: "\(microserviceBaseURL)/send-sms")
        
        // Make the request to the microservice
        let response = try await httpClient.post(url) { req in
            try req.content.encode(payload)
            req.headers.contentType = .json
        }
        
        // Check response status
        guard response.status == .ok else {
            // Try to extract error message from response
            struct ErrorResponse: Content {
                let success: Bool
                let message: String
            }
            
            let errorResponse = try? response.content.decode(ErrorResponse.self)
            throw Abort(
                .internalServerError,
                reason: "短信发送失败: \(errorResponse?.message ?? "未知错误")"
            )
        }
    }
} 